package com.hoperun.product.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.AidcManager.CreatedCallback;
import com.honeywell.aidc.BarcodeReader;
import com.hoperun.distributecloth.R;
import com.hoperun.product.base.BaseActivity;
import com.hoperun.product.entity.UserBean;
import com.hoperun.product.net.IServiceImpl;
import com.hoperun.product.net.RequestServiceImpl;
import com.hoperun.product.util.LanguageUtil;
import com.hoperun.product.util.MD5Encrypt;
import com.hoperun.product.util.ParseUtils;
import com.hoperun.product.util.SharedPreUtil;
import com.hoperun.product.view.SimpleDialog;
import com.zhuyu.downloadlibrary.DownloadDialog;
import com.zhuyu.downloadlibrary.UpdateInfoBizData;

import org.json.JSONObject;

public class LoginActivity extends BaseActivity implements OnClickListener {

	private Button loginBtn;
	private EditText accountEt;
	private EditText passwordEt;
	private TextView versionTv;
	private Button languageBtn;
	//棉纱库存
	private Button  mianshakucunBtn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		initDate();
		initView();
		initEvent();
		getNewVersion();
	}

	private void initDate() {

	}

	private void initView() {
		loginBtn = (Button) findViewById(R.id.login_loginBtn);
		accountEt = (EditText) findViewById(R.id.login_accountEt);
		passwordEt = (EditText) findViewById(R.id.login_passwordEt);
		mianshakucunBtn= findViewById(R.id.mianshakucunBtn);
		languageBtn=findViewById(R.id.languageBtn);
		versionTv= findViewById(R.id.versionTv);
		versionTv.setText("version："+AppUtils.getAppVersionName());
	}

	private void initEvent() {
		loginBtn.setOnClickListener(this);
		languageBtn.setOnClickListener(view -> {
			LanguageUtil.changeLanguage();

		});
		mianshakucunBtn.setOnClickListener(v -> {
			startActivity(new Intent(LoginActivity.this,CottonYarnStorageActivity.class));
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_loginBtn:
			startLogin();
			break;
		}
	}

	private void startLogin() {
		// accountEt.setText("9999");
		// passwordEt.setText("abc123");

		String account = accountEt.getText().toString();

		String password = MD5Encrypt.MD5(passwordEt.getText().toString());

		if (TextUtils.isEmpty(account)) {
			toast(getResources().getString(R.string.input_account));
			return;
		}
		if (TextUtils.isEmpty(password)) {
			toast(getResources().getString(R.string.input_password));
			return;
		}
		showWait();
		RequestServiceImpl.login(mMIPHandler, IServiceImpl.LOGIN_R, account, password);
	}

//	private static com.honeywell.aidc.BarcodeReader barcodeReader;
//	private AidcManager manager;
//
//	private void initBarcode() {
//		AidcManager.create(this, new CreatedCallback() {
//
//			@Override
//			public void onCreated(AidcManager aidcManager) {
//				manager = aidcManager;
//				barcodeReader = manager.createBarcodeReader();
//
//			}
//		});
//
//	}
//
//	public static BarcodeReader getBarcodeObject() {
//		return barcodeReader;
//	}



	/**
	 * 获取新版本
	 */
	private void getNewVersion() {
		showWait();
		final  String appname="分布app";
		RequestServiceImpl.getNewVersion(mMIPHandler, IServiceImpl.GET_NEW_VERSION,appname);
	}


	@Override
	public void onPostHandle(int requestType, Object objBody, boolean error) {

		stopWait();
		String opt = "";
		String msg = "";

		if (error) {
			switch (requestType) {
				case IServiceImpl.GET_NEW_VERSION:
					try {


						JSONObject jsonObj = new JSONObject((String) objBody);
						opt = jsonObj.optString("OPT_FLAG");
						JSONObject data = jsonObj.optJSONObject("DATA");
						msg = jsonObj.optString("MSG_INFO");
						if ("SUCCESS".equals(opt) && data != null) {
							UpdateInfoBizData bizData = ParseUtils.parse(data.toString(), UpdateInfoBizData.class);
							if (bizData != null) {
								final String url = bizData.getAndroidUrl();
							//final String url ="http://gdown.baidu.com/data/wisegame/caf555e29862078f/wangyixinwen_1026.apk";
							//	final String url ="http://192.168.0.108:8080/zhuyu/DistributeClothV0.5(125).apk";

								String version = bizData.getAndroidversionCode();
								String curVersion = AppUtils.getAppVersionName();
								String forceUpdate = bizData.getAndroidForced();
								String filename = url.substring(url.lastIndexOf("/")+1);
								// 文件保存在应用关联缓存目录
								String filePath=this.getExternalFilesDir(null)+"/"+filename;
								if (!curVersion.equals(version)) {

									if ("1".equals(forceUpdate)) {
										SimpleDialog.forceShow(this, getResources().getString(R.string.application_has_new_version_need_force_update), new SimpleDialog.OnPositiveClickListener() {

											@Override
											public void onPositiveClick() {
												DownloadDialog dowDialog = DownloadDialog.newInstance(url,filePath, true);
												dowDialog.setDownloadListener(new DownloadDialog.DownloadSimpleListener() {

													@Override
													public void onSuccess() {
														AppUtils.installApp(filePath);
													}

													@Override
													public void onError() {
														SimpleDialog.show(LoginActivity.this, getResources().getString(R.string.download_fail));
													}
												});
												dowDialog.show(getSupportFragmentManager(), "DownLoad");


											}
										});
									} else {
										SimpleDialog.show(this, getResources().getString(R.string.application_has_new_version_need_update), new SimpleDialog.OnNegativeClickListener() {

											@Override
											public void onNegativeClick() {

											}
										}, new SimpleDialog.OnPositiveClickListener() {

											@Override
											public void onPositiveClick() {
												DownloadDialog dowDialog = DownloadDialog.newInstance(url, filePath,false);
												dowDialog.setDownloadListener(new DownloadDialog.DownloadSimpleListener() {

													@Override
													public void onSuccess() {
														AppUtils.installApp(filePath);
													}

													@Override
													public void onError() {
														SimpleDialog.show(LoginActivity.this, getResources().getString(R.string.download_fail));
													}
												});
												dowDialog.show(getSupportFragmentManager(), "DownLoad");


											}
										});
									}
								}

							}

						} else {
							if (TextUtils.isEmpty(msg)) {
								SimpleDialog.show(this, getResources().getString(R.string.no_update_config_please_contact_manager));
							} else {
								SimpleDialog.show(this, msg);
							}

						}


					} catch (Exception e) {
						e.printStackTrace();
						toast(getResources().getString(R.string.data_parse_exception)+ e.toString());
					}
					break;
			case IServiceImpl.LOGIN_R:
				try {
					// 需注意这里判断登录失败不能去解析json，服务端只会返回单字符串“FALSE”

					if ("FALSE".equals(objBody.toString())) {
						SimpleDialog.show(this, getResources().getString(R.string.login_fail_and_check_account_password));
						return;
					}

					JSONObject jsonObj = new JSONObject((String) objBody);
					opt = jsonObj.optString("OPT_FLAG");
					if ("SUCCESS".equals(opt)) {

						JSONObject userbeanObj = jsonObj.optJSONObject("userBean");
						// 保存userbean数据到本地，格式为json字符串
						SharedPreUtil.putValue(this, SharedPreUtil.USERBEAN, userbeanObj.toString());

						UserBean userBean = new UserBean();
						userBean = ParseUtils.parse(userbeanObj.toString(), UserBean.class);
						String YHM = userBean.XTYHBean.YHM;
						// 保存YHM 员工工号
						SharedPreUtil.putValue(this, SharedPreUtil.YHM, YHM);
						// //保存权限代码
						// JSONArray QXCOMMArray=
						// jsonObj.optJSONArray("QXCOMM");
						// //闲置空
						// SharedPreUtil.putValue(this,
						// SharedPreUtil.CM0140202,"");
						// for (int i = 0; i < QXCOMMArray.length(); i++) {
						// JSONObject QXCOMMObj=QXCOMMArray.getJSONObject(i);
						// String CM0140202=QXCOMMObj.optString("CM0140202");
						// if(!TextUtils.isEmpty(CM0140202)){
						// SharedPreUtil.putValue(this,
						// SharedPreUtil.CM0140202,CM0140202);
						// break;
						// }
						// }

						Intent intent = new Intent(this, ChooseActivity.class);
						startActivity(intent);

						// finish();
					} else {
						SimpleDialog.show(this,  getResources().getString(R.string.login_fail_and_check_account_password));
					}

				} catch (Exception e) {
					e.printStackTrace();
					toast(getResources().getString(R.string.data_parse_exception)+ e.toString());
				}
				break;
			}
		} else {
			switch (requestType) {
			case IServiceImpl.GET_NEW_VERSION:
				toast(objBody.toString());
				break;
				case IServiceImpl.LOGIN_R:
					toast(objBody.toString());
					break;

			}

		}
	}
	
//	   @Override
//	    protected void onDestroy() {
//	        super.onDestroy();
//
//	        if (barcodeReader != null) {
//	            // close BarcodeReader to clean up resources.
//	            barcodeReader.close();
//	            barcodeReader = null;
//	        }
//
//	        if (manager != null) {
//	            // close AidcManager to disconnect from the scanner service.
//	            // once closed, the object can no longer be used.
//	            manager.close();
//	        }
//	    }

}
